package com.yht.redbookauth.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {

    @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
        //使用SpringBoot自带的线程池
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        threadPoolTaskExecutor.setCorePoolSize(10);
        // 设置最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(50);
        // 设置队列容量
        threadPoolTaskExecutor.setQueueCapacity(200);
        // 设置线程的空闲时间
        threadPoolTaskExecutor.setKeepAliveSeconds(30);
        // 设置线程名称前缀
        threadPoolTaskExecutor.setThreadNamePrefix("AuthExecutor-");
        // 设置拒绝策略(由调用线程处理，一般为主线程)
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 线程池在关闭时是否等待所有任务完成
        threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        // 设置线程池在关闭时等待任务完成的最大时间，确保应用最后能够被关闭，而不是被没有完成的任务阻塞
        threadPoolTaskExecutor.setAwaitTerminationSeconds(60);

        threadPoolTaskExecutor.initialize();

        return threadPoolTaskExecutor;
    }
}
